<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <!-- 为 my-goods 组件动态绑定 goods 属性的值 -->
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    reactive,
    ref
  } from 'vue'
  import {
    onLoad,
    onReachBottom,
    onPullDownRefresh
  } from '@dcloudio/uni-app'
  // 获取商品列表数据的方法
  const getGoodsList = async (queryObj, goodsList, total, isloading) => {
    // ** 打开节流阀
    isloading.value = true
    // 发起请求
    const {
      data: res
    } = await uni.$http.get('/api/public/v1/goods/search', queryObj)
    // ** 关闭节流阀
    isloading.value = false
    uni.stopPullDownRefresh()
    if (res.meta.status !== 200) return uni.$showMsg()
    if (res.message.goods.length == 0) return uni.$showMsg("已经到底了...")
    // 为数据赋值：通过展开运算符的形式，进行新旧数据的拼接
    goodsList.value = [...goodsList.value, ...res.message.goods]
    total.value = res.message.total
  }
  export default {
    setup() {
      // 请求参数对象
      const queryObj = reactive({
        // 查询关键词
        query: '',
        // 商品分类Id
        cid: '',
        // 页码值
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 10
      })
      // 商品列表的数据
      const goodsList = ref([])
      // 总数量，用来实现分页
      const total = ref(0)
      // 是否正在请求数据
      const isloading = ref(false)
      // 页面加载时触发,一个页面只会调用一次,可以在onload参数中获取打开当前页面路径中的参数
      onLoad((options) => {
        // 将页面参数转存到 this.queryObj 对象中
        queryObj.query = options.query || ''
        queryObj.cid = options.cid || ''
        getGoodsList(queryObj, goodsList, total, isloading)
      })
      // 触底的事件
      onReachBottom(() => {
        // 判断是否正在请求其它数据，如果是，则不发起额外的请求
        if (isloading.value) return
        // 让页码值自增 +1
        queryObj.pagenum += 1
        // 重新获取列表数据
        getGoodsList(queryObj, goodsList, total, isloading)
      })
      onPullDownRefresh(()=>{
          //  重置关键数据
          queryObj.pagenum = 1
          total.value = 0
          isloading.value = false
          goodsList.value = []
          //  重新发起请求
          getGoodsList(queryObj, goodsList, total, isloading)
      })
      // 点击跳转到商品详情页面
      const gotoDetail = (item) => {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
      return {
        goodsList,
        gotoDetail
      }
    }
  }
</script>

<style lang="scss">
  .goods-item {
    display: flex;
    padding: 10px 5px;
    border-bottom: 1px solid #f0f0f0;

    .goods-item-left {
      margin-right: 5px;

      .goods-pic {
        width: 100px;
        height: 100px;
        display: block;
      }
    }

    .goods-item-right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .goods-name {
        font-size: 13px;
      }

      .goods-price {
        font-size: 16px;
        color: #c00000;
      }
    }
  }
</style>
